package com.gz.mylife.app;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;

import com.gz.mylife.Define;
import com.gz.mylife.R;
import com.gz.mylife.adapter.BaseAdapterHelper;
import com.gz.mylife.adapter.QuickAdapter;
import com.gz.mylife.widget.FooterView;
import com.gz.mylife.widget.LoadingCover;
import com.gz.mylife.widget.OfflineDialog;
import com.gz.mylife.widget.FooterView.OnFooterViewRefreshListener;
import com.gz.mylife.widget.LoadingCover.OnLoadingCoverRefreshListener;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshBase.OnRefreshListener;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.assist.ImageScaleType;
import com.zl.smartmall.library.ISmartMall;
import com.zl.smartmall.library.listener.GetAssortProductslListener;
import com.zl.smartmall.library.listener.RequestCode;
import com.zl.smartmall.library.po.AssortProducts;
import com.zl.smartmall.library.util.CrashHandler;


public class AssortmentProductsActivity extends BaseActivity implements OnClickListener, OnFooterViewRefreshListener, OnItemClickListener, OnLoadingCoverRefreshListener, OnRefreshListener<ListView> {

	private static final String TAG = AssortmentProductsActivity.class.getSimpleName();
	private int mBrandId;
	private int mPage;
	private Context mContext;
	private DisplayImageOptions mIconOption;
	private QuickAdapter<AssortProducts> mAdapter;
	
	private FooterView mFooterView;
	private LoadingCover mLoadingCover;
	private PullToRefreshListView mListView;
	private LayoutInflater mInflater;
	private OfflineDialog mOfflineDialog;
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.fragment_mall_branded_products);
		setActionbarTitle(this.getIntent().getStringExtra("typename"), false);
		mInflater = getLayoutInflater();
		init();
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
			return super.onOptionsItemSelected(item);
//		}
	}



	@Override
	public void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		CrashHandler.d(TAG, TAG + " onDestory");
	}


	@Override
	public void onPause() {
		// TODO Auto-generated method stub
		super.onPause();
		CrashHandler.d(TAG, TAG + " onPause");
	}

	@Override
	public void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		CrashHandler.d(TAG, TAG + " onResume");
	}	
	
	@Override
	public void onStart() {
		// TODO Auto-generated method stub
		super.onStart();
	}
	
	@Override
	public void onStop() {
		// TODO Auto-generated method stub
		super.onStop();
	}
	
	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
		
		}
	}

	@Override
	public void onLoadingCoverRefresh() {
		// TODO Auto-generated method stub
		loadDataFromServer(buildListener(RequestCode.PULL));
	}

	@Override
	public void onFooterViewRefresh() {
		// TODO Auto-generated method stub
		loadDataFromServer(buildListener(RequestCode.SCROLL));
	}

	@Override
	public void onItemClick(AdapterView<?> parent, View view, int position,
			long id) {
		// TODO Auto-generated method stub
		if(view == mFooterView) {
			return;
		}
		Intent intent = new Intent(mContext, ProductDetail.class);
		intent.putExtra("productId", mAdapter.getItem((int) id).getProductId());
		intent.putExtra("shopId", mAdapter.getItem((int) id).getShopId());
		intent.putExtra("mBrandId", mBrandId);
		startActivity(intent);
	}

	@Override
	public void onRefresh(PullToRefreshBase<ListView> refreshView) {
		// TODO Auto-generated method stub
		loadDataFromServer(buildListener(RequestCode.PULL));
	};
	
	private QuickAdapter<AssortProducts> buildAdater(){
		return new QuickAdapter<AssortProducts>(mContext, R.layout.fragment_mall_branded_products_product_item, new ArrayList<AssortProducts>()) {

			@Override
			protected void convert(BaseAdapterHelper helper, AssortProducts item) {
				helper.setImageUrl(R.id.iv_product, item.getProductIcon(), mIconOption)
					  .setText(R.id.tv_product_intro, item.getProductIntro())
					  .setText(R.id.tv_current_cost, "￥" + new DecimalFormat("0.00").format(item.getCurrentCost()))
					  .setText(R.id.shop_time, "已售  " + item.getSaleNum())
					  .setText(R.id.tv_shop_name, item.getShopName());
			}
		};
	}
	
	private DisplayImageOptions buildIconOptions(){
		return new DisplayImageOptions.Builder()
		.resetViewBeforeLoading(true)
        .bitmapConfig(Bitmap.Config.ARGB_8888)
        .cacheInMemory(true)
        .cacheOnDisk(true)
        .showImageOnLoading(R.drawable.ic_load_image_square_default)
        .showImageOnFail(R.drawable.ic_load_image_square_fail)
        .showImageForEmptyUri(R.drawable.ic_load_image_square_fail)
        .imageScaleType(ImageScaleType.EXACTLY)
        .build();
	}
	
	private GetAssortProductslListener buildListener(RequestCode requestCode) {
		return new GetAssortProductslListener(requestCode) {
			
			@Override
			public void onResponseFailed() {
				// TODO Auto-generated method stub
				mLoadingCover.onRefreshFailed();
				if(mListView.isRefreshing()) {
					mListView.getLoadingLayoutProxy().refreshFailed();
				}
			}
			
			@Override
			public void onOffline() {
				// TODO Auto-generated method stub
				mLoadingCover.onRefreshFailed();
				mOfflineDialog.show();
				mLoadingCover.onRefreshFailed(Define.MSG_OFFLINE_ERROR);
				if (mListView.isRefreshing()) {
					mListView.getLoadingLayoutProxy().refreshFailed();
				}
			}
			
			@Override
			public void onNoMoreData() {
				// TODO Auto-generated method stub
				mLoadingCover.onRefreshFailed(Define.MSG_NOTHING);
				mFooterView.onRefreshComplete();
				mListView.setOnScrollListener(null);
				if(mListView.isRefreshing()) {
					mListView.getLoadingLayoutProxy().refreshSuccess();
				}
				if(requestCode == RequestCode.PULL) {
					mAdapter.clear();
				}
			}
			
			@Override
			public void onResponseSuccess(
					List<AssortProducts> brandedProductsInfos) {
				// TODO Auto-generated method stub
				if(this.requestCode == RequestCode.PULL) {
					mAdapter.clear();
				}
				mAdapter.addAll(brandedProductsInfos);
				//mAdapter.notifyDataSetChanged();
				if (brandedProductsInfos.size() < Define.LISTVIEW_ITEM_MIN_SIZE) {
					mFooterView.onRefreshComplete();
					mListView.setOnScrollListener(null);
					
				} else {
					mFooterView.onRefreshSuccess();
					mListView.setOnScrollListener(mFooterView);
				}
				if(mListView.isRefreshing()) {
					mListView.getLoadingLayoutProxy().refreshSuccess();
				}
				mLoadingCover.onRefreshSuccess();
			}

			@Override
			public void onNoNetWork() {
				// TODO Auto-generated method stub
				if(mListView.isRefreshing()) {
					mListView.getLoadingLayoutProxy().refreshFailed();
				}
				mFooterView.onRefreshFailed();
				mLoadingCover.onRefreshFailed(Define.MSG_NO_NETWORK);
			}
		};
	}
	
	private void init(){
		mBrandId = this.getIntent().getIntExtra("brandId", 0);
		mContext = this.getApplicationContext();
		mAdapter = buildAdater();
		mIconOption = buildIconOptions();
		mFooterView = (FooterView) mInflater.inflate(R.layout.footer_view, null);
		mFooterView.setOnFooterViewRefreshListener(this);
		mLoadingCover = (LoadingCover) findViewById(R.id.layout_loading_cover);
		mLoadingCover.setOnLoadingCoverRefreshListener(this);
		mListView = (PullToRefreshListView) findViewById(R.id.list);
		mListView.getRefreshableView().addFooterView(mFooterView);
		mListView.setAdapter(mAdapter);
		mListView.setOnRefreshListener(this);
		mListView.setOnItemClickListener(this);
		mListView.setOnScrollListener(mFooterView);
		mOfflineDialog = (OfflineDialog) getLayoutInflater().inflate(R.layout.offline_dialog, null);
		
		
		loadDataFromServer(buildListener(RequestCode.PULL));
	}
	
	private void loadDataFromServer(GetAssortProductslListener ProductsListener) {		
		if(ProductsListener.getRequestCode() == RequestCode.PULL) {
			mPage = 1;
		}else if(ProductsListener.getRequestCode() == RequestCode.SCROLL) {
			mPage++;
		}
		ISmartMall.getInstance().getAssortProductsList(mBrandId, mPage, ProductsListener);
	}
}
